package com.novax.ex.activity.provider.handler.consumer;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.novax.ex.activity.infrastructure.entity.RankStandings;
import com.novax.ex.activity.infrastructure.mapper.RankStandingsMapper;
import com.novax.ex.activity.provider.api.model.ExcelRankStandings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 交易赛导入excel更新排名监听器
 * @Author ChenXi
 * @Date 2023/11/23/16:18
 */

@Slf4j
public class RankExcelListener extends AnalysisEventListener<ExcelRankStandings> {

    private Long rankSubId;
    private RankStandingsMapper rankStandingsMapper;
    private List<RankStandings> rankStandingsList = new ArrayList<>();


    public RankExcelListener(Long rankSubId, RankStandingsMapper rankStandingsMapper) {
        this.rankSubId = rankSubId;
        this.rankStandingsMapper = rankStandingsMapper;
    }

    @Override
    public void invoke(ExcelRankStandings excelRankStandings, AnalysisContext analysisContext) {
        RankStandings rankStandings = excelConvert(excelRankStandings, rankSubId);
        rankStandingsList.add(rankStandings);
    }

    @Override
    @Transactional(rollbackFor =  RuntimeException.class)
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        rankStandingsMapper.batchInsert(rankStandingsList);
    }

    /**
     * @param excelRankStandings
     * @Description: Excel实体转换
     * @Author: ChenXi
     * @Date: 2023/11/23 16:38
     * @return: com.novax.ex.activity.infrastructure.entity.RankStandings
     **/
    private RankStandings excelConvert(ExcelRankStandings excelRankStandings, Long rankSubId) {
        RankStandings rankStandings = new RankStandings();
        try {
            Integer ranked = Integer.parseInt(excelRankStandings.getRanked().replace(" ", "").replace("\u00A0", ""));
            Long userId = Long.parseLong(excelRankStandings.getUserId().replace(" ", "").replace("\u00A0", ""));
            BigDecimal tradeProfit = new BigDecimal(excelRankStandings.getTradeProfit().replace(" ", "").replace("\u00A0", "").replace("%", ""));
            BigDecimal rewardEstimate = new BigDecimal(excelRankStandings.getRewardEstimate().replace(" ", "").replace("\u00A0", ""));

            rankStandings.setRankSubId(rankSubId);
            rankStandings.setRanked(ranked);
            rankStandings.setUserId(userId);
            rankStandings.setTradeProfit(tradeProfit);
            rankStandings.setRewardEstimate(rewardEstimate);
        } catch (NumberFormatException e) {
            log.error("解析异常 error",e);
        }
        return rankStandings;
    }
}
